package com.ruoyi.web.netty;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.spring.SpringContextHolder;
import com.ruoyi.xqsp.domain.MsgsCollectArchived;
import com.ruoyi.xqsp.domain.SpUsers;
import com.ruoyi.xqsp.service.ISpUsersService;
import com.ruoyi.xqsp.service.MsgsCollectArchivedService;
import io.netty.channel.*;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.springframework.beans.factory.annotation.Autowired;

import java.net.SocketAddress;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

public class CoordinationSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {


    MsgsCollectArchivedService msgsCollectArchivedService = SpringContextHolder.getBean(MsgsCollectArchivedService.class);
    RedisCache redisCache = SpringContextHolder.getBean(RedisCache.class);
    ISpUsersService spUsersService = SpringContextHolder.getBean(ISpUsersService.class);

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("与客户端建立连接，通道开启！");

        SocketAddress socketAddress = ctx.channel().remoteAddress();
        System.out.println("socketAddress = " + socketAddress);
        Channel channel = ctx.channel();
        ChannelId id = channel.id();
        System.out.println("id = " + id);
        //添加到channelGroup通道组
        CoordinationChannelHandlerPool.channelGroup.add(ctx.channel());


    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("与客户端断开连接，通道关闭！");

//        String s = redisCache.getCacheObject(ctx.channel().id().toString());
//        SpUsers spUsers = new SpUsers();
//        spUsers.setUserLoginState(0);
//        spUsers.setUserId(Long.valueOf(s));
//        spUsersService.updateById(spUsers);
//        OnlineProcessor.getInstance().putUser();
        //从channelGroup通道组删除
        CoordinationChannelHandlerPool.channelGroup.remove(ctx.channel());
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        //接收的消息
        SocketAddress socketAddress = ctx.channel().remoteAddress();
        System.out.println("socketAddress = " + socketAddress);
        System.out.println(String.format("收到客户端%s的数据：%s", ctx.channel().id(), msg.text()));

        System.out.println(msg.text());
        System.out.println(msg.text().toString());
        Protocal protocal = JSONObject.parseObject(msg.text(), Protocal.class);
        switch (protocal.type){
            case 0:
                Channel onlineSession = OnlineProcessor.getInstance().getOnlineSession(protocal.getTo());

                //存储聊天记录
                MsgsCollectArchived msgsCollectArchived = new MsgsCollectArchived();
                msgsCollectArchived.setSrcUid(protocal.getFrom());
                msgsCollectArchived.setDestUid(protocal.getTo());
                msgsCollectArchived.setMsgType(protocal.getMsgType());
                msgsCollectArchived.setMsgContent(protocal.getDataContent());


                msgsCollectArchivedService.save(msgsCollectArchived);
                if(onlineSession != null){
                    System.out.println(String.format("向客户端%s的数据：%s", onlineSession.id(), msg.text()));
                    ChannelFuture channelFuture = onlineSession.writeAndFlush(new TextWebSocketFrame(msg.text()));

                }

//                System.out.println("channelFuture = " + channelFuture);
                break;
            case 1:
                OnlineProcessor.getInstance().putUser(protocal.getFrom(),ctx.channel());
                SpUsers spUsers = new SpUsers();
                spUsers.setUserLoginState(1);
                spUsers.setUserId(Long.valueOf(protocal.getFrom()));
                spUsersService.updateById(spUsers);
                redisCache.setCacheObject(ctx.channel().id().toString(),protocal.getFrom());
//                redisCRUD.setObject(protocal.getFrom(),ctx.channel(),-1);
                break;
            case 2:
                OnlineProcessor.getInstance().removeUser(protocal.getFrom());
                break;
        }


        // 单独发消息
//        {"type":"1","from":"43"}
//        {"type":"0","from":"44","to":"44", "msgType":"1","dataContent":{"from":"44","fromName":"发送者的昵称","fromAvatar":发送者的头像",to":"44","toName":"接收者的昵称", "msgType":"1","msg":"测试数据222"}}
        // 群发消息
//        sendAllMessage();
    }

    private void sendMessage(ChannelHandlerContext ctx) throws InterruptedException {
        String message = "我是服务器，你好呀";
        ctx.writeAndFlush(new TextWebSocketFrame("hello"));
    }

    private void sendAllMessage() {
        String message = "我是服务器，这是群发消息";
        CoordinationChannelHandlerPool.channelGroup.writeAndFlush(new TextWebSocketFrame(message));
    }


}
